import 'dart:convert';
import 'dart:io';

import 'package:device_info/device_info.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_niandaxue/config/device.dart';
import 'package:flutter_niandaxue/model/base_model.dart';
import 'package:flutter_niandaxue/pages/index_page.dart';
import 'package:flutter_niandaxue/pages/login_page.dart';
import 'package:flutter_niandaxue/service/http_service.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:package_info/package_info.dart';
import 'package:url_launcher/url_launcher.dart';

class StartApp extends StatefulWidget{
  @override
  _StartAppState createState() => _StartAppState();
}

class _StartAppState extends State<StartApp> {
  var loginState;

  void initState() {
    super.initState();
    _validateLogin();
    _initDeviceInfo();
    _getCurrentNewVersion();
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)
      ..init(context);

//    final router = Router();
//    Routes.configureRoutes(router);
//    Application.router = router;
    if (loginState == null || loginState == '' || loginState == 0) {
      return LoginPage();
    } else {
      return IndexPage();
    }
  }

  Future _validateLogin() async {
    Future<dynamic> future = getTokenLocal();
    future.then((val) {
      if (val == null || val == '') {
        setState(() {
          loginState = 0;
        });
      } else {
        setState(() {
          loginState = 1;
        });
      }
    }).catchError((_) {
//      print("catchError");
    });
  }

  // 初始化设备信息
  void _initDeviceInfo() async {
    DeviceInfoPlugin deviceInfo = new DeviceInfoPlugin();
    int deviceType = 0;
    String deviceId = '';
    if (Platform.isIOS) {
      KDevice.deviceType = 2;
      IosDeviceInfo iosDeviceInfo = await deviceInfo.iosInfo;
      KDevice.deviceId = iosDeviceInfo.identifierForVendor;
    } else if (Platform.isAndroid) {
      KDevice.deviceType = 3;
      AndroidDeviceInfo androidDeviceInfo = await deviceInfo.androidInfo;
      KDevice.deviceId = androidDeviceInfo.androidId;
    }
  }

  // 获取系统版本信息
  _getCurrentNewVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String _version = packageInfo.version; //版本名
    var param = '/' + KDevice.deviceType.toString();
    request_get_json('version/currentNew', formData: param).then((val) {
      var data = json.decode(val.toString());
      setState(() {
        VersionInfo _newVersionInfo = VersionInfo.fromJson(data['data']);
        String _currentNewVersion = _newVersionInfo.versionNum;
        int versionFlag = _newVersionInfo.versionFlag;
        if (_version != _currentNewVersion && _currentNewVersion != "") {
          _openAlertDialog("", versionFlag: versionFlag,
              downLoadUrl: _newVersionInfo.downLoadUrl);
        }
      });
    });
  }

  // 打开弹框
  Future _openAlertDialog(content,
      {int versionFlag, String downLoadUrl}) async {
    String msg = content;
    if (versionFlag != null) {
      msg = versionFlag == 1 ? "本次版本为强制更新版本，否则将无法使用，是否升级" : "发现新版本，是否升级";
    }

    final action = await showDialog(
      context: context,
      barrierDismissible: false, //// user must tap button!
      builder: (BuildContext context) {
        return AlertDialog(
//          title: Text('提示'),
          content: Text(msg),
          actions: <Widget>[
            FlatButton(
              child: Text('取消'),
              onPressed: () {
                if (versionFlag != null && versionFlag == 1) {
                  SystemNavigator.pop();
                } else {
                  Navigator.pop(context, Action.Cancel);
                }
              },
            ),
            FlatButton(
              child: Text('确认'),
              onPressed: () {
                if (versionFlag != null && downLoadUrl != null) {
                  _updateVersionUrl(downLoadUrl);
                } else {
                  Navigator.pop(context, Action.Cancel);
                }
              },
            ),
          ],
        );
      },
    );
  }

  // 升级到最新版本, 通过浏览器下载
  _updateVersionUrl(url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      _showToast("更新失败，请稍后再试");
    }
  }

  // 提示信息
  void _showToast(msg) {
    Fluttertoast.showToast(
      msg: msg,
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.BOTTOM,
      timeInSecForIos: 1,
    );
  }
}

enum Action {
  Ok,
  Cancel
}